package com.example._9_springmvc.xzy.aop;

import com.example._9_springmvc.xzy.pojo.LoginLog;
import com.example._9_springmvc.xzy.service.impl.LoginLogServiceImpl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Map;

@Aspect
@Component
public class LoginLogAspect {
    @Autowired
    private LoginLogServiceImpl loginLogService;
    @Pointcut("@annotation(com.example._9_springmvc.xzy.aop.LoginLogAnno)")
    public void loginLog() {
    }
    @AfterReturning(pointcut = "loginLog()", returning = "result")
    public void logPoinCut(JoinPoint joinPoint, Object result) throws SQLException, ClassNotFoundException {
        ModelAndView modelAndView = (ModelAndView) result;
        if (modelAndView.getViewName().equals("main")) {
            Object[] args = joinPoint.getArgs();
            HttpServletRequest request = (HttpServletRequest) args[0];
            String username = (String) request.getSession().getAttribute("username");
            String loginIP = (String) request.getSession().getAttribute("loginIP");
            String loginTime = (String) request.getSession().getAttribute("loginTime");
            LoginLog loginLog = new LoginLog();
            loginLog.setUserName(username);
            loginLog.setLoginIP(loginIP);
            loginLog.setLoginTime(loginTime);
            loginLogService.LoginLogSave(loginLog);
        }
    }

}
